﻿namespace BathroomLocator.Services.Infrastructure
{
	using System;
	using System.IO;
	using System.Text;
	using System.Text.RegularExpressions;
	using System.Web;
	using System.Xml;

	public static class StorageRequestAnalyzer
	{
		public static string GetRequestedTable(HttpRequest request)
		{
			var path = request.PathInfo;

			if (path.ToUpperInvariant().Contains("/TABLES("))
			{
				var match = Regex.Match(path, @"tables\(['""](\w+)['""]\)", RegexOptions.IgnoreCase);

				if (match.Groups.Count > 1)
				{
					return match.Groups[1].Value;
				}
			}
			else
			{
				var slashPos = path.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
				var parenthesisPos = path.IndexOf("(", StringComparison.OrdinalIgnoreCase);
				parenthesisPos = (parenthesisPos == -1) ? path.Length - 1 : parenthesisPos - 1;

				if (slashPos > -1)
				{
					return path.Substring(slashPos + 1, parenthesisPos - slashPos);
				}
				else
				{
					return path;
				}
			}

			return string.Empty;
		}

		public static string GetTableToCreate(HttpRequest request)
		{
			var table = string.Empty;
			var buffer = new byte[request.InputStream.Length];
			request.InputStream.Read(buffer, 0, (int)request.InputStream.Length);
			request.InputStream.Seek(0, SeekOrigin.Begin);

			var body = ASCIIEncoding.ASCII.GetString(buffer);

			var xml = new XmlDocument();
			xml.LoadXml(body);

			var tableEl = xml.GetElementsByTagName("d:TableName");

			if (tableEl.Count > 0)
			{
				table = tableEl[0].InnerText;
			}

			return table;
		}

		public static bool IsCreatingTable(HttpRequest request, string tableName)
		{
			if (tableName.Equals("Tables", StringComparison.OrdinalIgnoreCase))
			{
				if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}

			return false;
		}
	}
}